package cn.ubeta.b2c;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;

import cn.ubeta.b2c.common.AnalyseActivity;
import cn.ubeta.b2c.common.CartCommon;
import cn.ubeta.b2c.navigation.FoundFragment;
import cn.ubeta.b2c.navigation.HomeFragment;
import cn.ubeta.b2c.navigation.MeFragment;
import cn.ubeta.b2c.settings.SettingsActivity;
import cn.ubeta.b2c.widget.TitleBar;
import com.kevin.tabindicator.TabPageIndicatorEx;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by denny on 16/8/17.
 */

public class HomeActivity extends AnalyseActivity implements CartCommon.ICartListener {

    public static final String PARAM_TAB = "tab";

    private ViewPager mViewPager;
    private TabPageIndicatorEx mTabPageIndicatorEx;
    private List<Fragment> mTabs = new ArrayList<>();
    private FragmentPagerAdapter mAdapter;
    private TitleBar mTitleBar;

    private TabInfo[] mTabInfo = {
            new TabInfo(HomeFragment.class, "主页", R.drawable.brand_icon),
            new TabInfo(FoundFragment.class, "发现"),
            /*
            new TabInfo(CartFragment.class, "购物车"),
            */
            new TabInfo(MeFragment.class, "我的")};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        initViews();
        initEvents();

        // TODO 待删除,测试代码
        initTestData();
    }

    @Override
    public String getPageName() {
        return "主页";
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // 检查h5模板更新
        //UpdateHelper.checkH5ModelUpdate(this);
        // 检查是否展示开机引导图
        /* TODO 暂时关闭开机引导
        if (AppConfig.needRunGuide()) {
            GuideActivity.gotoGuide(this);
        } else {
            // 检查更新
            //UpdateHelper.checkUpdate(this);
        }
        */
    }

    /**
     * TODO 初始化测试数据,待删除
     */
    private void initTestData() {
        // 购物车个数
        if (DemoData.getCartInfo() != null)
            CartCommon.setCartCount(DemoData.getCartInfo().getCount());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mViewPager == null && mOnPageChangeListener != null)
            mViewPager.removeOnPageChangeListener(mOnPageChangeListener);
        CartCommon.removeListener(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        notifyShopCartCountChanged(CartCommon.getCartCount(), false);
    }

    @Override
    public void notifyShopCartCountChanged(int count, boolean showAnimation) {
        /*
        if (mTabPageIndicatorEx != null) {
            String text = count > 0 ? (count > 99 ? "99+" : String.valueOf(count)) : null;
            mTabPageIndicatorEx.setIndicateDisplayText(2, text);
        }
        */
    }

    /**
     * 初始化View
     */
    private void initViews() {
        mTitleBar = (TitleBar) findViewById(R.id.title_bar);
        mViewPager = (ViewPager) findViewById(R.id.vp_page);
        mTabPageIndicatorEx = (TabPageIndicatorEx) findViewById(R.id.tab_indicator);
        initTabIndicator();
        initViewPager();

        // 初始化标题栏图标
        mTitleBar.setIcon(mTabInfo[0].resIcon);
        mTitleBar.setLeftClickListener(v -> finish());
    }

    /**
     * 初始化viewpager
     */
    private void initViewPager() {
        for (TabInfo tabInfo : mTabInfo) {
            Fragment tabFragment = null;
            try {
                tabFragment = tabInfo.clazz.newInstance();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
            if (tabFragment == null) {
                Log.e("Home", "tabFragment == null");
                finish();
                return;
            }
            //Bundle args = new Bundle();
            //tabFragment.setArguments(args);
            mTabs.add(tabFragment);
        }

        mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {

            @Override
            public int getCount() {
                return mTabs.size();
            }

            @Override
            public Fragment getItem(int arg0) {
                return mTabs.get(arg0);
            }
        };
        mViewPager.setAdapter(mAdapter);
        // 设置缓存3页,这样4个tab页都不会销毁
        mViewPager.setOffscreenPageLimit(3);

        // 跳转tab
        int tabIndex = getIntent().getIntExtra(PARAM_TAB, 0);
        if (tabIndex >= mTabInfo.length || tabIndex < 0)
            tabIndex = 0;

        mTabPageIndicatorEx.setTabsDisplay(tabIndex);
        mViewPager.setCurrentItem(tabIndex, false);
    }

    /**
     * 初始化事件
     */
    private void initEvents() {
        mTabPageIndicatorEx.setOnTabSelectedListener(index -> {
            mViewPager.setCurrentItem(index, false);
        });
        mViewPager.addOnPageChangeListener(mOnPageChangeListener);
    }

    private ViewPager.OnPageChangeListener mOnPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {

            // 更新购物车数字的颜色(FIX:左右滑动时不变色)
            mTabPageIndicatorEx.setTabsDisplay(position);

            // 设置标题文字或者图标
            if (mTabInfo[position].resIcon != 0)
                mTitleBar.setIcon(mTabInfo[position].resIcon);
            else
                mTitleBar.setTitle(mTabInfo[position].title);

            /* TODO 暂时屏蔽设置
            if (mTabInfo[position].clazz == MeFragment.class) {
                mTitleBar.setAction("设置", mActionListener);
            } else {
                mTitleBar.setAction(null, null);
            }
            */
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    };

    private View.OnClickListener mActionListener = view -> {
        // 进入设置页
        SettingsActivity.gotoActivity(this, SettingsActivity.class);
        overridePendingTransition(R.anim.in_right_to_left, android.R.anim.fade_out);
    };

    /**
     * 初始化底部Tab
     */
    private void initTabIndicator() {
        mTabPageIndicatorEx.setViewPager(mViewPager);

        // 渐变
        mTabPageIndicatorEx.setIsGradualChange(true);

        // 监听购物车
        CartCommon.addListener(this);
    }

    /**
     * 跳转到主页
     */
    public static void gotoHome(Context context) {
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.setClassName(context, context.getString(R.string.app_activity));
        context.startActivity(intent);
    }

    class TabInfo {
        String title;
        int resIcon;
        Class<? extends Fragment> clazz;
        int resLayout;

        public TabInfo(Class<? extends Fragment> clazz, String title) {
            this(clazz, title, 0);
        }

        public TabInfo(Class<? extends Fragment> clazz, String title, int resIcon) {
            this(clazz, title, resIcon, 0);
        }

        public TabInfo(Class<? extends Fragment> clazz, String title, int resIcon, int resLayout) {
            this.title = title;
            this.resIcon = resIcon;
            this.clazz = clazz;
            this.resLayout = resLayout;
        }
    }
}
